<template>
  <div id="information">
    <div class="top-title flex-center s-18 ">完善个人信息
      <!--<div class="close" @click="close">-->
      <!--<img src="../../assets/img/login/close.png" alt="">-->
      <!--</div>-->
    </div>
    <div class="steps  flex-center" v-if="this.eduLevelType==='primary'">
      <div :class="['steps-item',active===0?'active': 'dactive']">
        <div class="steps-num s-14 flex-center" v-if="active===0">1</div>
        <img style="width: 28px;height: 28px;margin-right: 14px;" v-else src="../../assets/img/home/step-complate.png" alt="">
        <div class="s-18 in-tips" :style="active===0? '':'color: #65C239;'">填写信息</div>
      </div>
      <div class="steps-line"></div>
      <div :class="['steps-item',active===1?'active': 'dactive']">
        <div class="steps-num s-14 flex-center">2</div>
        <div class="s-18 in-tips">选择教材</div>
      </div>
    </div>
    <el-form :model="userIformation" ref="messageForm" label-width="92px" label-position="right" style="margin-top:15px" v-if="active===0">
      <el-form-item label="填写姓名">
        <el-input v-model.trim="userIformation.fullName" placeholder="输入姓名" style="width:360px"></el-input>
      </el-form-item>
      <el-form-item label="选择地区">
        <el-select v-model="userIformation.province" placeholder="选择省" :popper-append-to-body="false">
          <el-option v-for="item in provinces" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="userIformation.city" placeholder="选择市" :popper-append-to-body="false">
          <el-option v-for="item in cities" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="userIformation.district" placeholder="选择区" :popper-append-to-body="false">
          <el-option v-for="item in districts" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="教师类型">
        <el-select v-model="userIformation.teacherType" placeholder="选择教师类型" :popper-append-to-body="false">
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择学校">
        <el-select v-model="userIformation.eduLevelId" placeholder="选择学段" :popper-append-to-body="false">
          <el-option v-for="item in eduLevel" :key="item.id" :label="item.eduLevelName" :value="item.eduLevelId">
          </el-option>
        </el-select>
        <div class="code-container">
          <el-input placeholder="输入学校名关键字搜索" v-model="userIformation.schoolName" style="width:346px"></el-input>
          <div class="get-code tips" @click="search">搜索</div>
        </div>
        <!-- <span class="s-12 t-color-c"> <span class="t-color-e">*</span> 学段信息选择后不可修改</span> -->
      </el-form-item>
      <el-form-item prop="schoolName" :rules="{validator: validatePass, trigger: 'blur' }">
        <div class="search-result">
          <div class="search-tips flex-center" v-if="!searchIsclick">
            <span class="s-16">请先选择省市区、学段</span>
          </div>
          <div v-show="searchArry.length===0 && searchIsclick && !addSchool" class="search-tips flex-center  s-18">
            <!-- <div class="search-tips flex-center s-18"> -->
            <span class="s-16" style="color: black">暂无搜索结果，请更换关键字或 <span class="addSchool s-14" @click="addSchoolMethod">点击创建学校</span></span>
          </div>
          <div v-if="addSchool" class="add-input">
            <el-input v-model="userIformation.schoolName" class="bottom-input-div" placeholder="输入你的学校" style="width: 226px; height: 40px;">
            </el-input>
          </div>
          <div class="scholl-list" v-if="searchArry.length>0 && searchIsclick">
            <div v-for="v in searchArry" :key="v.id" :class="userIformation.schoolId !== v.id ? 'bottom-input-div' : 'bottom-input-div-selected'" @click="selectSchool(v.id, v.name)">{{v.name}}</div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div v-if="active===1" class="textbook">
      <div class="flex-between">
        <div>
          <span style="margin-right: 14px" class="new-user-tips s-14">选择教材版本</span>
          <el-select v-model="category" placeholder="选择教材版本" :popper-append-to-body="false" @change="selectPublish">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="new-user-tips s-14">
          *新用户可免费体验
          <span class="s-18" style="color:#E9A139">3</span>
          本教材
        </div>
      </div>

      <div class="book">
        <div v-for="(v,i) in bookList" :key="v.id" class="book-item" :data-index="i" @click="check(i)">
          <img :src="v.thumb" alt="加载失败">
          <div class="book-message">{{v.name}}</div>
          <div class="checked" v-if="v.checked">
            <img src="../../assets/img/home/checked.png" alt="">
          </div>
        </div>
      </div>


    </div>
    <button v-if="active===0" :class="['dis-button' , 'next-btn' ,{'use-btn':!disNext}]" :disabled="disNext" @click="nextStep">{{btnName}}</button>
    <button v-if="active===1" :class="['dis-button',  'complete-btn', {'use-btn':disSubmit}]" :disabled="!disSubmit" @click.prevent="submit">完成</button>
  </div>
</template>

<script>
import school from '@/content/api/school'
import user from '@/content/api/user'
import store from '@/content/store/index.js'
import { SqlLibUser } from "../../../../../static/lib/sqlite/service/SqlLibUser";
import { SqlLib } from "../../../../../static/lib/sqlite/SqlLib";
import { updateUserMessage } from '../../utils/event'
import { Ini } from '../../utils/ini';
const cryUtil = require('../../../../../static/utils/CrypUtil');
export default {
    name: 'information',
    props: ['isInformation'],
    inject: ["refreshHomePage"],
    computed: {
        cities() {
            let arry = []
            this.provinces.some((v, i, arr) => {
                if (v.id === this.userIformation.province) {
                    arry = arr[i].cities
                    return true
                }
            })
            return arry
        },
        districts() {
            let arry = []
            this.cities.some((v, i, arr) => {
                if (v.id === this.userIformation.city) {
                    arry = arr[i].districts
                    return true
                }
            })
            return arry
        },
        disNext() {
            if (!this.userIformation.province || !this.userIformation.city ||
                !this.userIformation.district || !this.userIformation.eduLevelId || !this.userIformation.fullName) {
                return true;
            } else {
                if (this.addSchool) {//如果是添加学校，必须有学校名称且学校名称才亮显
                    if (this.userIformation.schoolName && this.isLegitimate) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (this.userIformation.schoolId) {
                        return false;
                    } else {
                        return true;
                    }
                }
            }
        },
        disSubmit() {
            return !this.disNext;
        },
        btnName() {
            if (this.eduLevelType === 'primary') {
                return '下一步'
            } else {
                return '完成'
            }
        }
    },
    watch: {
        'userIformation.province'() {
            this.userIformation.city = ''
            this.userIformation.district = ''
            this.searchArry = [];
            this.addSchool = false;
        },
        'userIformation.city'() {
            this.userIformation.district = ''
            this.searchArry = [];
            this.addSchool = false;
        },
        'userIformation.district'() {
            if (this.userIformation.district === '') {
                this.searchArry = [];
                this.addSchool = false;
                this.userIformation.schoolName = '';
                this.userIformation.schoolId = '';
            }
        },
        userIformation: {
            handler(val, oldVal) {
                if (val.province && val.city && val.district && val.eduLevelId) {
                    if (!this.addSchool && !val.schoolName && !val.schoolId) {//不是添加学校，且学校名称不为空，执行自动搜索
                        this.search();
                    }
                }
            },
            deep: true
        }
    },
    data() {
        return {
            active: 0,
            category: '',
            categoryList: [],
            userIformation: {
                fullName: '',
                province: '',
                city: '',
                teacherType:'',
                district: '',
                eduLevelId: '',
                schoolName: '',
                schoolId: ''
            },
            typeList:[
              {
                label:'专职',
                value:0
              },
              {
                label:'兼职',
                value:1
              },
              {
                label:'其他',
                value:null
              },
            ],
            provinces: [],
            eduLevel: [],
            searchArry: [],
            bookList: [],
            addSchool: false,
            searchIsclick: false,
            checked: [],
            eduLevelType: Ini.readIni('data', 'eduLevel'),
            legitimateSchoolName:this.$CONST.global.legitimateSchoolName,
            isLegitimate:false,
        }
    },
    mounted() {
        let _this = this;
        school.getAllArea().then(areas => {
            if (areas.code == "0") {
                _this.provinces = areas.returnValue.provinces;
                school.getEduLevels().then(eduLevels => {
                    if (areas.code == "0") {
                        _this.eduLevel = [];
                        let currentEduLevels = eduLevels.returnValue;
                        let currentVersion = _this.$readIniFile('data', 'eduLevel');
                        currentEduLevels.forEach((eduLevel, index) => {
                            if (currentVersion == 'primary') {//如果是小学学段
                                if (eduLevel.eduLevelId == _this.$CONST.global.eduLevel.primary) {
                                    _this.eduLevel.push(eduLevel);
                                    _this.userIformation.eduLevelId = eduLevel.eduLevelId;
                                }
                            } else {
                                if (eduLevel.eduLevelId == _this.$CONST.global.eduLevel.high ||
                                    eduLevel.eduLevelId == _this.$CONST.global.eduLevel.junior) {
                                    _this.eduLevel.push(eduLevel);
                                }
                            }
                        });
                    }
                });
            }
        })
    },
    methods: {
        //验证用户添加的学校是否合法
        validatePass(rule, value, callback){
            if(!this.addSchool) {
                this.isLegitimate = true
                callback()
            }else{
                if(!value) return callback()
                let reg = new RegExp(/^[\u4e00-\u9fa5][〇\u4e00-\u9fa5]+[\u4e00-\u9fa5]$/,'g')
                if(!reg.test(value)){
                    this.isLegitimate = false
                    callback(new Error('请输入正确的学校中文全称，例如xx附属小学，xx第一中学'))
                }else{
                    let flag =  this.legitimateSchoolName.some(item => {
                        return value.includes(item)
                    })
                    if(flag){
                        this.isLegitimate = true
                        callback()
                    }else{
                        this.isLegitimate = false
                        callback(new Error('请输入正确的学校中文全称，例如xx附属小学，xx第一中学'))
                    }
                }
            }
        },
        addSchoolMethod() {
            this.addSchool = true;
            this.userIformation.schoolId = "";
        },
        search() {
            //查询接口
            let _this = this;
            //每次点击搜索，就把添加学校置为false
            this.addSchool = false;
            this.userIformation.schoolId = "";
            this.searchIsclick = true
            const params = {
                districtId: this.userIformation.district,
                eduLevelId: this.userIformation.eduLevelId
            };
            if (this.userIformation.schoolName) {
                params.schoolName = this.userIformation.schoolName;
            }
            school.getSchoolsByAreaId(params).then(res => {
                if (res.returnValue) {
                    _this.searchArry = res.returnValue
                } else {
                    _this.searchArry = []
                }
            });
        },
        submit() {
            if (this.checked.length < 3) {
                this.$dialog({
                    confirm: '放弃',
                    cancel: '取消',
                    message: `您还可以免费体验${3 - this.checked.length}本教材，是否放弃选择？`,
                    close: false,
                    type: "warn"
                }).then(_ => {
                    this.submitInformation()
                })
            } else {
                this.submitInformation()
            }
        },
        submitInformation() {
            let _this = this;
            const params = {
                fullName: this.userIformation.fullName,
                teacherType:this.userIformation.teacherType,
                bookIds: this.checked
            }
            if (this.addSchool) {
                params.schoolName = this.userIformation.schoolName;
                params.districtId = this.userIformation.district;
                params.eduLevelId = this.userIformation.eduLevelId;
            } else {
                params.schoolId = this.userIformation.schoolId;
            }
            user.perfectUserInfo(params).then(response => {
                if (response.code == "0") {
                    user.getUserInfo({}).then(userInfo => {
                        if (userInfo.code == "0") {
                            userInfo = userInfo.returnValue;
                            let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                            user.schoolId = userInfo.schoolId;
                            user.eduLevelId = userInfo.eduLevelId;
                            user.schoolName = userInfo.schoolName;
                            user.name = userInfo.userBaseVO.fullName;
                            user.bookId = userInfo.bookId;
                            user.vipType = cryUtil.aesEncrypt(userInfo.isVip + "", user.id + "", true);
                            user.remainderDays = cryUtil.aesEncrypt(userInfo.days + "", user.id + "", true);
                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(user);
                            _this.close();
                            _this.refreshHomePage();
                            _this.$message.success("完善个人信息成功！");
                            updateUserMessage()
                        } else {
                            _this.$message.success("完善个人信息失败！");
                        }
                    }).catch(error => { _this.$message.error("网络异常！") })
                } else {
                    _this.$message.warning(response.message);
                }
            }).catch(error => { _this.$message.error("网络异常！") })
        },
        nextStep() {
            if (this.userIformation.teacherType === '') {
              this.$message.warning('请选择教师类型')
              return
            }
            if (this.eduLevelType === 'primary') {
                let _this = this;
                school.getAllPublisher().then(publishers => {
                    if (publishers.code == "0") {
                        let currentPub = publishers.returnValue;
                        _this.categoryList = [];
                        currentPub.forEach(publisher => {
                            if (_this.userIformation.eduLevelId == publisher.eduLevelId) {
                                _this.categoryList.push({
                                    id: publisher.id,
                                    name: publisher.name
                                });
                            }
                        })
                        _this.active = _this.active + 1;
                        _this.bookList = [];
                        if (_this.categoryList.length > 0) {
                            _this.category = _this.categoryList[0].id;
                            _this.selectPublish();
                        }
                    }
                }).catch(error => {
                    this.message.error("网络异常！");
                });
            }else{
                this.submitInformation()
            }

        },
        check(index) {
            let _this = this;
            if (this.bookList[index].checked) {
                this.bookList[index].checked = false
                let currentIndex = -1;
                this.checked.forEach((temp, curIndex) => {
                    if (temp === _this.bookList[index].id) {
                        currentIndex = curIndex;
                    }
                });
                if (currentIndex !== -1) {
                    _this.checked.splice(currentIndex, 1);
                }
            } else {
                if (this.checked.length < 3) {
                    this.$set(this.bookList[index], 'checked', true);
                    this.checked.push(_this.bookList[index].id);
                }
            }
        },
        close() {
            this.$emit('closeInformation', false)
        },
        selectSchool(schoolId, schoolName) {
            this.userIformation.schoolId = schoolId;
            this.userIformation.schoolName = schoolName;
        },
        selectPublish() {
            let _this = this;
            const param = {
                publisherId: this.category
            }
            school.getBooksByPublisherId(param).then(books => {
                let currentBooks = books.returnValue;
                _this.bookList = [];
                currentBooks.forEach(book => {
                    let curChecked = false;
                    if (_this.checked.length > 0) {
                        _this.checked.forEach(temp => {
                            if (temp === book.id) {
                                curChecked = true;
                            }
                        })
                    }
                    _this.bookList.push({
                        id: book.id,
                        name: book.name,
                        thumb: book.thumb,
                        checked: curChecked
                    })
                })
            })
        }
    }
}
</script>

<style lang="scss">
#information {
  width: 900px;
  height: 680px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  padding-bottom: 30px;
  .el-select-dropdown {
    width: 160px !important;
  }
  .el-select-dropdown__empty {
    font-size: 14px !important;
  }
  .el-popper .popper__arrow {
    visibility: hidden;
    display: none;
  }
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .el-select-dropdown__item {
    border-radius: 8px;
    margin: 2px 8px;
    padding: 0 12px;
    font-size: 14px !important;
  }
  .el-select-dropdown__item.selected {
    color: #4793ff;
    background-color: rgba(71, 147, 255, 0.1);
    border-radius: 8px;
    margin: 0 8px;
    padding: 0 12px;
  }
  .el-input__inner {
    border-radius: 8px;
    font-size: 14px !important;
    &::-webkit-input-placeholder {
      font-size: 14px;
    }
  }
  .el-form-item {
    margin-bottom: 20px;
    .el-input {
      margin-left: 35px;
    }

    .el-select:nth-child(n + 2) {
      margin-left: 20px;
    }
  }
  .el-select {
    width: 160px;
  }
  .el-form-item__label {
    padding: 0;
    font-size: 14px;
    line-height: 40px;
  }
  .el-form-item__content {
    line-height: 40px;
  }
  .add-input {
    .el-input {
      margin: 0;
    }
  }
  .top-title {
    width: 100%;
    height: 64px;
    background-color: #f4f4f4;
    position: relative;
    .close {
      top: 10px;
      right: 10px;
      position: absolute;
      img {
        width: 9px;
        height: 9px;
      }
    }
  }
  .steps {
    margin-top: 30px;
    .steps-item {
      display: flex;
      align-items: center;
      cursor: default;
    }
    .steps-line {
      width: 100px;
      height: 1px;
      background-color: #dddfe7;
      margin: 0 2.14px;
    }
  }
  .dactive {
    .steps-num {
      margin-right: 14px;
      width: 28px;
      height: 28px;
      border: 2px solid #5f6165;
      border-radius: 50%;
    }
    .in-tips {
      color: #5f6165;
    }
  }
  .active {
    .steps-num {
      margin-right: 14px;
      width: 28px;
      height: 28px;
      border: 2px solid #4793ff;
      border-radius: 50%;
      background-color: #4793ff;
      color: #fff;
    }
    .in-tips {
      color: #4793ff;
    }
  }
  .code-container {
    position: relative;
    display: inline-block;
    margin-left: 20px;
    .el-input__inner {
      padding-right: 60px;
    }
  }
  .get-code {
    position: absolute;
    font-size: 14px;
    right: 21px;
    top: 0;
  }
  .search-result {
    width: 734px;
    height: 210px;
    background: #eff3f7;
    border-radius: 8px;
    padding: 18px;
    margin-left: 35px;
    overflow: auto;
    .search-tips {
      height: 100%;
      width: 100%;
      color: #c1ceda;
    }
    .addSchool {
      display: inline-block;
      margin-left: 12px;
      color: #4793ff;
      border-bottom: 1px solid #4793ff;
      line-height: 23px;
    }
  }
  .scholl-list {
    display: grid;
    grid-template-columns: repeat(3, 226px);
    grid-template-rows: repeat(3, 40px);
    grid-gap: 12px 12px;
  }
  .bottom-input-div {
    background: #fff;
    border-radius: 8px;
    text-align: center;
    .el-input__inner {
      background-color: #fff;
      border: #fff;
      border-radius: 8px;
    }
  }
  .bottom-input-div-selected {
    background: #4893ff;
    border-radius: 8px;
    text-align: center;
    color: #ffffff;
    .el-input__inner {
      background-color: #fff;
      border: #fff;
      border-radius: 8px;
    }
  }
  .next-btn {
    width: 120px;
    height: 40px;
    display: block;
    margin: 0 auto;
  }
  .complete-btn {
    display: block;
    width: 120px;
    height: 40px;
    margin: 40px auto 0 auto;
  }
  .textbook {
    padding: 0 40px;
    // overflow-y: scroll;
    .new-user-tips {
      color: rgba(95, 97, 101, 1);
      line-height: 40px;
      margin: 20px 0;
    }
  }
  .book {
    height: 360px;
    overflow-y: scroll;
    overflow-x: hidden;
    display: flex;
    flex-wrap: wrap;
    // display: grid;
    // grid-template-columns: repeat(6, 115px);
    // grid-template-rows: repeat(6, 162px);
    // grid-gap: 26px 26px;
    margin-bottom: 10px;
  }
  .book-item {
    width: 115px;
    height: 162px;
    margin: 10px 10px;
    position: relative;
    img {
      width: 100%;
      height: 100%;
    }
    .book-message {
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 35px;
      line-height: 35px;
      text-align: center;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.6);
    }
    .checked {
      height: 127px;
      width: 100%;
      background-color: rgba(0, 0, 0, 0.6);
      position: absolute;
      top: 0;
      img {
        width: 34px;
        height: 34px;
        position: absolute;
        top: 160px;
        right: 0;
        transform: translate(50%, -50%);
      }
    }
  }
}
@media screen and(max-width:1439px) {
  #information {
    width: 750px;
    height: 533px;
    padding-bottom: 15px;
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
    .top-title {
      height: 45px;
    }
    .steps {
      margin: 15px 0;
      .steps-item {
        display: flex;
        align-items: center;
        cursor: default;
      }
      .steps-line {
        width: 100px;
        height: 1px;
        background-color: #dddfe7;
        margin: 0 2.14px;
      }
    }
    .search-result {
      width: 600px;
      height: 180px;
      background: #eff3f7;
      border-radius: 8px;
      padding: 18px;
      margin-left: 35px;
      overflow: auto;
      .search-tips {
        height: 100%;
        width: 100%;
        color: #c1ceda;
      }
      .addSchool {
        display: inline-block;
        margin-left: 12px;
        color: #4793ff;
        border-bottom: 1px solid #4793ff;
        line-height: 23px;
      }
    }
    .scholl-list {
      display: grid;
      grid-template-columns: repeat(3, 178px);
      grid-template-rows: repeat(3, 40px);
      grid-gap: 12px 12px;
    }
    .textbook {
      padding: 0 40px;
      .new-user-tips {
        color: rgba(95, 97, 101, 1);
        line-height: 40px;
        margin: 10px 0;
      }
    }
    .book {
      height: 300px;
      display: grid;
      grid-template-columns: repeat(6, 92px);
      grid-template-rows: repeat(6, 130px);
      grid-gap: 26px 26px;
    }
    .book-item {
      .book-message {
        height: 20px;
        font-size: 12px;
        line-height: 20px;
      }
      .checked {
        height: 110px;
        top: 0;
        img {
          width: 22px;
          height: 22px;
          position: absolute;
          top: 128px;
        }
      }
    }
  }
}
</style>
